package com.zhilianbao.leyaogo.ui.fragment.goodscategory;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import com.bql.convenientlog.CLog;
import com.bql.fragmentation.anim.DefaultNoAnimator;
import com.bql.fragmentation.anim.FragmentAnimator;
import com.bql.slidedetails.SlideDetailsLayout;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.category.GoodsDetails;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品信息页面
 * Created by gyt on 2016/11/1
 */
public class GoodsInfoFragment extends BaseOkHttpFragment implements GoodsInfoBottomFragment.OnFabClickListener {

    @BindView(R.id.slide_details)
    SlideDetailsLayout mSlideDetails;
    // 是否第一次打开bottom详情页
    private boolean mIsFirst = true;
    // 是否Load fragment完成
    private boolean mLoad = false;
    private int mGoodsId;
    private int mGoodsSkuId;


    public static GoodsInfoFragment getInstance(Bundle bundle) {
        GoodsInfoFragment fragment = new GoodsInfoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void initToolbarHere() {
    }

    /**
     * 在viewPager的fragment中，要调用该方法否则initViewsAndEvents不会调用
     *
     * @return
     */
    @Override
    protected FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultNoAnimator();
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mGoodsId = getArguments().getInt(IntentConfig.BUNDLE_GOODS_ID);
            mGoodsSkuId = getArguments().getInt(IntentConfig.BUNDLE_GOODS_SKU_ID);
            getGoodsDetails();
        }

    }


    private void getGoodsDetails() {
        CategoryApi.getGoodsDetail(mActivity, mGoodsId, mGoodsSkuId, new LoadingViewCallback<GoodsDetails>(mActivity, getView(), false) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                getGoodsDetails();
            }

            @Override
            public boolean isShowLoading() {
                return true;
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                EventBus.getDefault().post(new EventManager<String>(LeEventCode.MSG_CODE_GET_GOODS_DETAILS_ERROR));
            }

            @Override
            public void onResultSuccess(GoodsDetails goodsDetails, @Nullable Response response, LoadingViewCallback callback) {
                EventBus.getDefault().post(new EventManager<GoodsDetails>(LeEventCode.MSG_CODE_GET_GOODS_DETAILS_SUCS, goodsDetails));
                // 只会load一次fragment，之后调用getGoodsDetails只是为了获取goodsDetails数据
                if (!mLoad) {
                    GoodsInfoTopFragment topFragment = GoodsInfoTopFragment.getInstance(goodsDetails);
                    loadRootFragment(R.id.slide_details_Top, topFragment);
                    mLoad = true;
                    // lambda表达式
                    mSlideDetails.setOnSlideDetailsListener(status -> {
                        boolean statusClose = status == SlideDetailsLayout.Status.CLOSE ? true : false;
                        topFragment.setOpenIndicator(statusClose);
                        GoodsFragment mParentFragment = (GoodsFragment) mActivity.getFragmentation().findStackFragment(GoodsFragment.class, getFragmentManager(), false);
                        mParentFragment.isViewPagerEnable(statusClose);
                        mParentFragment.changeToolbarStatus(statusClose);
                        if (!statusClose && mIsFirst) {//只有SlideDetailsLayout打开后并且是第一次进来，才加载GoodsInfoBottomFragment
                            List<String> goodsPics = Utils.getGoodsFiles(goodsDetails, 1);
                            CLog.i("goodsPicSize = " + goodsPics.size());
                            GoodsInfoBottomFragment bottomFragment = GoodsInfoBottomFragment.getInstance(goodsPics);
                            bottomFragment.setOnFabClickListener(GoodsInfoFragment.this);
                            loadRootFragment(R.id.slide_details_bottom, bottomFragment);
                            mIsFirst = false;
                        }
                    });
                }
                }

        });

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_goods_info;
    }

    @Override
    public boolean onBackPressedSupport() {
        // 如果下拉进入web页面，则返回关闭webView
        if (mSlideDetails.getStatus() == SlideDetailsLayout.Status.OPEN) {
            onFabClick(null);
            return true;
        } else {
            return super.onBackPressedSupport();
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_LOGIN_SUCCESS) {
            getGoodsDetails();
        }
    }

    /**
     * 点击返回顶部按钮，SlideDetailsLayout关闭，并且scrollView定位到顶部
     *
     * @param view
     */
    @Override
    public void onFabClick(View view) {
        FrameLayout topView = (FrameLayout) mSlideDetails.getTopView();
        ScrollView scrollView = (ScrollView) topView.getChildAt(0);
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                // scrollView定位到顶部
                scrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        });

        mSlideDetails.smoothClose(true);
    }
}
